package com.user.server;

import com.common.utils.CommonUtils;
import com.common.utils.Result;
import com.user.mapper.UserMapper;
import com.user.pojo.dto.UserDto;
import com.user.pojo.entity.User;
import com.user.pojo.vo.UserVo;
import com.user.server.impl.UserServerImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class UserServer implements UserServerImpl {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * 新增用户
     * * * */
    @Override
    public Result newUser(UserDto userDto) {
       UserVo userVo= userMapper.selectUeser(userDto.getInviter());
       if (userVo==null){
           return Result.error("注册必须要有邀请人");
       }
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setInvite(CommonUtils.getRandomLong());
        Integer status= userMapper.insertUser(user);
        if (status>0){
            return Result.success("创建成功");
        }
        log.error("新增用户失败");
        return Result.error("创建用户失败，请稍后重新再试");
    }

    /**
     * 查看用户详情
     * * * */
    @Override
    public Result selectUserDetail(long useId) {
        UserVo userVo= userMapper.selectUserDetail(useId);
        return Result.success(userVo);
    }

    /**
     * 删除用户
     * * * */
    @Override
    public Result deleteUser(long userId) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        Integer a= userMapper.delete(userId);
       if (a>0){
           return Result.success("注销成功");
       }
        return Result.error("注销失败");
    }
}
